<template>
  <!-- 拓客线索 -->
  <div>
    <el-card>
      <div class="page-title">
        <span>拓客线索</span>
      </div>

      <div style="margin-top: 20px;">
        <el-form ref="queryForm" :model="queryForm" size="small">
          <el-row style="display: flex;flex-wrap: wrap;">
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item prop="selectDate">
                <el-date-picker v-model="queryForm.selectDate"
                                end-placeholder="结束日期"
                                format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期"
                                style="width: 100%;" type="daterange"
                                value-format="yyyy-MM-dd" @change="(val) => dateChange(val, { fileBytes: ['startDate', 'endDate'] }, 'queryForm')"/>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item prop="dataFrom">
                <el-select v-model="queryForm.dataFrom" clearable placeholder="数据来源" style="width: 100%;">
                  <el-option v-for="item in dataFromList" :key="item.dictValue" :label="item.dictLabel"
                             :value="item.dictValue"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item prop="ocLeadName">
                <el-input v-model="queryForm.ocLeadName" clearable placeholder="号码库名称" style="width: 100%;"/>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item>
                <div style="float: right;">
                  <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">查 询</el-button>
                  <el-button icon="el-icon-refresh" plain size="mini" type="info" @click="handleReset">重 置</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <el-card style="margin-top: 20px;">
      <div style="float: right;margin-bottom: 15px;">
        <el-button icon="el-icon-top" size="mini" type="primary" @click="toSend" v-has-permi="['admin:ioc:add']">上传数据</el-button>
      </div>
      <el-table v-loading="loading" :data="tableList" height="442px">
        <el-table-column align="center" label="号码库信息" min-width="120" prop="ocLeadName"/>
        <el-table-column align="center" label="ID" prop="ocLeadNo"/>
        <el-table-column align="center" label="创建时间" min-width="110" prop="createTime"/>
        <el-table-column align="center" label="数据来源" prop="dataFrom"/>
        <el-table-column align="center" label="上传数据" prop="inputCount"/>
        <el-table-column align="center" label="重复数据" prop="sameCount"/>
        <el-table-column align="center" label="黑名单数据" prop="blackCount"/>
        <el-table-column align="center" label="无效数据" prop="invalidCount"/>
        <el-table-column align="center" label="请求数据" prop="reqCount"/>
        <el-table-column align="center" label="通过数据/通过率" min-width="110" prop="passCount">
          <template slot-scope="scope">{{ scope.row.passCount }}/{{ scope.row.passRate }}</template>
        </el-table-column>
        <el-table-column align="center" label="未执行数据" min-width="90px" prop="unPursueCount"/>
        <el-table-column align="center" fixed="right" label="操作" min-width="120px" prop="">
          <template slot-scope="{ row }">
            <el-button size="mini" type="text" @click="downloadFile(row)" v-has-permi="['admin:phone:export']">下载数据</el-button>
            <el-button size="mini" type="text" @click="$router.push({ path: 'addDetails', query: { id: row.ocLeadNo, ocLeadName: row.ocLeadName} })">
              加人详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total"
                        @handleCurrentChange="handleCurrentChange"
                        @handleSizeChange="handleSizeChange"></NormalPagination>
    </el-card>


    <el-dialog :visible.sync="sendVisible" title="添加号码库" width="550px" :close-on-click-modal="false">
      <div class="top-toast">
        <i class="el-icon-warning"
           style="color: #082aff;margin: 0 10px;"></i><span>每个号码库上传上限制10万条数据</span>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="号码库名称" prop="ocLeadName">
          <el-input v-model="form.ocLeadName" clearable placeholder="不允许重复" style="width: 340px"/>
        </el-form-item>
        <el-form-item label="数据来源" prop="dataFrom">
          <el-radio-group v-model="form.dataFrom">
            <el-radio label="1" style="margin-right: 20px;">填写录入</el-radio>
            <el-radio label="2">Xlsx上传</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="">
          <el-input v-if="+form.dataFrom == 1" v-model="form.data" :rows="4" placeholder="格式”电话号码+逗号+备注名”例如: 13411112222,小李。回车键换行一行一条,不允许重复，每次添加上限1000条" style="width: 340px;"
                    type="textarea">
          </el-input>
          <div v-else class="xlsx-box">
            <span>1、<el-button type="text" @click="download">下载模板</el-button>，按格式准备需要导入的数据</span> <br>
            <span>2、上传需要导入的文件</span> <br>
            <el-upload ref="upload" :before-upload="beforeUpload" :file-list="fileList" :headers="upload.headers"
                       :http-request="uploadImage" :limit="1"
                       :on-exceed="handleExceed" :on-remove="handleRemove" :show-file-list="true" action="#">
              <el-button icon="el-icon-top" plain size="mini" style="margin-top: 5px;" type="info">选择Xlsx文件
              </el-button>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="sendVisible = false" :loading="uploadLoading">取 消</el-button>
        <el-button size="mini" type="primary" @click="submit" :loading="uploadLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {queryLeadList, queryOcLeadAdd} from '@/api/intelligentOutCall'
import {getToken} from "@/utils/auth";
import {downLoadFile} from "@/utils/common";
import moment from "moment";

export default {
  name: 'LeadGeneration',
  data() {
    return {
      sendVisible: false,
      loading: false,
      dataFromList: [
        {dictValue: '1', dictLabel: '填写录入'},
        {dictValue: '2', dictLabel: 'Xlsx上传'},
        {dictValue: '3', dictLabel: '公域投放'},
      ],
      form: {
        ocLeadName: '',
        dataFrom: '1',
        data: '',
      },
      rules: {
        ocLeadName: [{required: true, trigger: 'blur', message: '请输入外呼名称'},
          {max: 20, message: '名称输入有误，请重新输入', trigger: 'blur'}],
        dataFrom: [{required: true}]
      },
      queryForm: {
        selectDate: '',
        ocLeadName: '',
        dataFrom: null,
        startTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 20,
      },
      total: 0,
      tableList: [],
      fileList: [], //更新上传的文件列表
      upload: { // 更新上传文件的弹窗
        headers: {Authorization: 'Bearer ' + getToken()}
      },
      uploadLoading: false,
    }
  },
  methods: {
    getListFn() {
      let obj = {
        ...this.queryForm
      }
      this.loading = true
      queryLeadList(obj).then(res => {
        this.loading = false
        if (res.code == 200) {
          this.tableList = res.rows || [];
          this.total = res.total || 0;
        }
      }).catch(() => {
        this.loading = false
      })
    },
    downloadFile(row) {
      const params = {
        ocLeadNo: row.ocLeadNo,
      }
      let fileName = row.ocLeadName + '-' + moment(new Date()).format('YYYYMMDD') + '-' + row.ocLeadNo + '.xlsx'
      downLoadFile('/admin/oc/phone/export', params, fileName)
    },
    handleQuery() {
      this.queryForm.pageNum = 1
      this.getListFn()
    },
    handleReset() {
      this.queryForm = {
        selectDate: '',
        ocLeadName: '',
        dataFrom: null,
        startTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 20,
      }
      this.handleQuery()
    },
    download() {
      window.open(window.globalConfig.LEAD_ADD_TEMPLATE_URL)
    },
    submit() {
      if (this.form.dataFrom == '1' && !this.checkTextarea(this.form.data)) {
        console.log('进入这里了')
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.uploadLoading = true
          if (this.form.dataFrom == '1') {
            const formdata1 = new FormData()
            formdata1.append('ocLeadName', this.form.ocLeadName)
            formdata1.append('dataFrom', this.form.dataFrom)
            formdata1.append('data', this.form.data)
            queryOcLeadAdd(formdata1).then(res => {
              this.$message.success('添加成功')
              this.sendVisible = false
              this.uploadLoading = false
              this.handleQuery()
            }).catch(() => {
              this.uploadLoading = false
            })
          } else if (this.form.dataFrom == '2') {
            if (this.$refs.upload.$data.uploadFiles.length == 0) return this.$message.error('请上传要更新的文件')
            const formdata = new FormData()
            formdata.append('file', this.$refs.upload.$data.uploadFiles[0].raw)
            formdata.append('ocLeadName', this.form.ocLeadName)
            formdata.append('dataFrom', this.form.dataFrom)
            queryOcLeadAdd(formdata).then(res => {
              this.$message.success('添加成功')
              this.sendVisible = false
              this.uploadLoading = false
              this.handleQuery()
            }).catch(() => {
              this.uploadLoading = false
            })
          }
        }
      })
      // this.sendVisible = false
    },
    handleRemove() {

    },
    uploadImage() {

    },
    checkTextarea(str) {
      let reg = /^[1]([3-9])[0-9]{9}$/
      let arr = str.split('\n'), flag = true, arrSet = [...new Set(arr)];
      console.log('arr', arr, arrSet);
      if (arr.length != arrSet.length) return this.$message.error('有重复数据，请检查'), flag = false
      if (arr.length > 1000) return this.$message.error('每次添加上限1000条'), flag = false
      for (let i = 0; i < arr.length; i++) {
        const itemi = arr[i].replace(/，/g, ",");
        let arri = itemi.split(',')
        console.log(arri, arri.length, 'arri')
        if (arri.length != 2) return this.$message.error('录入格式错误'), flag = false
        let tel = arri[0];
        if (tel.length != 11) return this.$message.error(tel + '位数需为11位'), flag = false
        if (!reg.test(tel)) return this.$message.error(tel + '必需以13、14、15、16、17、18、19开头'), flag = false
      }
      console.log('1111', flag);
      return flag
    },
    textareaChange(key) {
      if (key.indexOf('，') > -1) key = key.replace(/，/g, ",");
      if (key.indexOf(' ') > -1) key = key.replace(/ /g, "");
      if (key.indexOf('\n') > -1) key = key.replace(/\n/g, ";");
      console.log(key);
      return key;
    },
    // 翻页
    handleSizeChange(value) {
      this.queryForm.pageNum = 1
      this.queryForm.pageSize = value
      this.getListFn()
    },
    handleCurrentChange(value) {
      this.queryForm.pageNum = value
      this.getListFn()
    },
    // range 日期change事件
    dateChange(val, item, byte) {
      let valNew = val || ["", ""];
      item.fileBytes.forEach((fileByte, index) => this.$set(this[byte], fileByte, valNew[index]));
    },

    // 文件上传前的钩子函数 可以对文件类型大小进行筛选
    beforeUpload(file) {
      console.log(file)
      let isXlS = false

      //上传格式限制
      const whiteList = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',//xlsx
      ]
      isXlS = whiteList.includes(file.type)
      if (!isXlS) {
        this.$message.error('仅支持xlsx格式文件！')
      }
      // 大小限制为10M
      const isLt10M = (file.size / 1024 / 1024 || 0) <= 10
      if (!isLt10M) {
        console.log(isLt10M, file.size / 1024 / 1024)
        this.$message.error('文件大小不得超过10MB！')
      }
      return isXlS && isLt10M
    },
    // 超出限制定义的方法
    handleExceed(file) {
      this.$message.error('已存在文件，请先删除后再上传！')
    },
    // 上传数据
    toSend(){
      this.sendVisible = true
      this.form = {
        ocLeadName: '',
        dataFrom: '1',
        data: '',
      }
      this.fileList = []
    },
  },
  mounted() {
    this.handleQuery()
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

.xlsx-box {
  padding: 9px 14px;
  border-radius: 2px;
  border: 1px solid #EEEEEE;
}

.top-toast {
  height: 30px;
  font-size: 12px;
  line-height: 30px;
  background: #EBEEFF;
  border-radius: 2px;
}

.page-title {
  font-size: 20px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #2A2A2A;
  margin-top: 10px;
  margin-left: 10px;
}
</style>
